package com.puff.service.impl;

import com.puff.constant.MessageConstant;
import com.puff.constant.StatusConstant;
import com.puff.dto.RiderLoginDTO;
import com.puff.dto.RiderRegisterDTO;
import com.puff.entity.Employee;
import com.puff.entity.Rider;
import com.puff.exception.AccountLockedException;
import com.puff.exception.AccountNotFoundException;
import com.puff.exception.PasswordErrorException;
import com.puff.mapper.RiderMapper;
import com.puff.service.RiderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
@Slf4j
public class RiderServiceImpl implements RiderService {

    @Autowired
    private RiderMapper riderMapper;

    /**
     * 骑手注册
     * @param riderRegisterDTO
     */
    public void register(RiderRegisterDTO riderRegisterDTO) {
        Rider rider = new Rider();

        BeanUtils.copyProperties(riderRegisterDTO,rider);

        String password = rider.getPassword();
        //将前端传过来的明文密码通过md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        rider.setPassword(password);
        riderMapper.insert(rider);

    }

    /**
     * 骑手登录
     * @param riderLoginDTO
     * @return
     */
    public Rider login(RiderLoginDTO riderLoginDTO) {
        String username = riderLoginDTO.getUsername();
        String password = riderLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Rider rider = riderMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (rider == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //e10adc3949ba59abbe56e057f20f883e
        //将前端传过来的明文密码通过md5加密，转化为密文的形式与数据库密码进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(rider.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //3、返回实体对象
        return rider;
    }

}
